package com.ming.javaweb.filter;

import com.ming.javaweb.beans.entity.AdminDO;
import com.ming.javaweb.util.ExcludeResourceUtil;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;


/**
 * @author Tcm
 */
@WebFilter(filterName = "AuthorizationFilter",
        urlPatterns = {"/*"}
)
public class AuthorizationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
       HttpServletRequest httpServletRequest = (HttpServletRequest) req;
//       过滤器排除静态资源/studentJavaWeb01
        String requestURI = httpServletRequest.getRequestURI();
        if (ExcludeResourceUtil.shouldExclude(requestURI)){
            filterChain.doFilter(req,resp);
        }else {
            HttpSession session = httpServletRequest.getSession();
            System.out.println("session:"+session.toString());
            AdminDO adminDO = (AdminDO) session.getAttribute("adminDo");
            String contextPath = httpServletRequest.getContextPath();
            String path = requestURI.substring(contextPath.length());
            if (adminDO == null){
                if ("/loginServlet".equals(path)){
                    filterChain.doFilter(req,resp);
                }else {//未登录且访问的路径不是公共路径
                    httpServletRequest.getRequestDispatcher("/pages/login.jsp")
                            .forward(req,resp);
                }
            }else {
                filterChain.doFilter(req,resp);
            }
        }
    }

    @Override
    public void destroy() {

    }
}

